package com.example.backgroundmanger.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.backgroundmanger.commons.Result;
import com.example.backgroundmanger.entity.Role;
import com.example.backgroundmanger.service.IRoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 坤哥
 * @since 2024-07-04
 */
@RestController
@RequestMapping("/role")
@Tag(name = "角色模块")
public class RoleController {
    @Resource
    private IRoleService roleService;

    @Operation(summary = "查询所有角色")
    @GetMapping("/getAllRole")
    public Result<List<Role>>  getAllRole(@RequestParam(value = "roleName",required = false) String roleName){
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasLength(roleName),Role::getRoleName,roleName);
        List<Role> list = roleService.list(wrapper);
        return Result.success(list);
    }

    @PostMapping("/updateAndSave")
    @Operation(summary = "新增/编辑")
    public Result<String> updateAndSave(@RequestBody Role role){
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Role::getRoleName,role.getRoleName());
        List<Role> list = roleService.list(wrapper);
        if(list.size()>=1){//用户名被占用
            return Result.error(409,"该角色被占用!");
        }

        if(role.getRoleId()==null){//新增
            roleService.save(role);
            return Result.success("新增成功!");
        }else{//编辑
            roleService.updateById(role);
            return Result.success("修改成功!");
        }
    }

    @DeleteMapping("/delDataById/{id}")
    @Operation(summary = "根据ID删除数据")
    //@PathVariable:占位符注解,该参数是来自请求地址的占位符
    public Result<String> delDataById(@PathVariable int id){
        roleService.removeById(id);
        return Result.success("删除成功");
    }

    @PostMapping("/delDataByIds")
    @Operation(summary = "批量删除")
    public Result<String> delDataByIds(@RequestBody List<Integer>  ids){
        roleService.removeBatchByIds(ids);
        return Result.success("批量删除成功!");
    }
}
